package com.wyz.socket.test.room;

import com.wyz.socket.core.impl.ConnectorHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AudioRoom {
    private final String roomCode;
    private volatile ConnectorHandler handler1;
    private volatile ConnectorHandler handler2;

    public AudioRoom() {
        this.roomCode = getRandomString(5);
    }

    private String getRandomString(int length) {
        Random random = new Random();
        final String str = "0123456789";
        final StringBuilder builder = new StringBuilder();
        for (int idx = 0; idx < length; idx++) {
            int number = random.nextInt(str.length());
            builder.append(str.charAt(number));
        }
        return builder.toString();
    }

    public ConnectorHandler getOtherHandler(ConnectorHandler handler) {
        return (handler1 == handler || handler1 == null) ? handler2 : handler1;
    }

    public synchronized boolean isEnableChat() {
        return handler1 != null && handler2 != null && handler1 != handler2;
    }

    public synchronized boolean joinRoom(ConnectorHandler handler) {
        if (handler1 == null) {
            handler1 = handler;
        } else if (handler2 == null) {
            handler2 = handler;
        } else {
            return false;
        }
        return true;
    }

    public synchronized ConnectorHandler exitRoom(ConnectorHandler handler) {
        if (handler1 == handler) {
            handler1 = null;
        } else if (handler2 == handler) {
            handler2 = null;
        }
        return handler1 == null ? handler2 : handler1;
    }

    public String getRoomCode() {
        return roomCode;
    }

    public ConnectorHandler[] getConnectors() {
        List<ConnectorHandler> handlers = new ArrayList<>(2);
        if (handler1 != null) {
            handlers.add(handler1);
        }
        if (handler2 != null) {
            handlers.add(handler2);
        }
        return handlers.toArray(new ConnectorHandler[0]);
    }
}
